import { app, BrowserWindow, dialog, screen, shell } from 'electron'
import {  optimizer } from '@electron-toolkit/utils'
import { checkUpdate, setDownloadWin } from './autoUpdate'
import { openWindow, getOpenUrl } from './windows'
import { ipcMain } from 'electron/main'
import icon from '../../resources/icon.png?asset'
import { resolve } from 'path'
import { startServer, killServer } from './codeGeneratorServer'
import { handleOffsetWindow } from './offsetWindow'
function focusWindow(win?: BrowserWindow): void {
  if (win) {
    win.moveTop();
    win.focus();
    win.show();
  }
}


const offsetWindowSize = 0; // 50
function main(): void {
  const { width, height } = screen.getPrimaryDisplay().workAreaSize
  let preloadWindow: Electron.BrowserWindow | null =  new BrowserWindow({
      width: 600,
      height: 300,
      show: false,
      frame: false,
      transparent: true,
      alwaysOnTop: true,
      skipTaskbar: true,
      icon,
      resizable: false,
      autoHideMenuBar: true,
      webPreferences: {
        preload: resolve(__dirname, '../preload/index.js'),
        sandbox: false
      }
  })
  preloadWindow.center()
  preloadWindow.loadURL(getOpenUrl('/app/preloading'))
  preloadWindow.on('closed', () => {
    preloadWindow = null;
  })
  preloadWindow.once('ready-to-show', () =>{
    preloadWindow!.show();
    startServer(preloadWindow!);
  })
  handleOffsetWindow();

  let mainWindow: Electron.BrowserWindow | null = null
  function createMainWindow() {
    if (mainWindow) {
      focusWindow(mainWindow);
      return;
    }
    preloadWindow?.close();
    mainWindow = openWindow({
      url: '/',
      width: 980 + offsetWindowSize * 2,
      height: 800 + offsetWindowSize * 2,
      // resizable: false
    })
    mainWindow?.center()
    mainWindow.setMinimumSize(980 + offsetWindowSize * 2, 800 + offsetWindowSize * 2)
    focusWindow(mainWindow);
  }

  ipcMain.on('application:select-file-path', (event) => {
    dialog.showOpenDialog({
      properties: ['openDirectory'],
    }).then(result => {
      event.sender.send('application:select-file-path-result', result.filePaths[0])
    }).catch(_err => {
      event.sender.send('application:select-file-path-result', '')
    })
  });

  ipcMain.on('application:open-main-window', createMainWindow);

  let dialogModalWindow: Electron.BrowserWindow | null = null
  ipcMain.on('application:open-dialog-modal', (event, data) => {
    if (dialogModalWindow && dialogModalWindow.isVisible()) {
      focusWindow(dialogModalWindow)
      return
    }
    dialogModalWindow = new BrowserWindow({
      width: data.width,
      height: data.height,
      show: false,
      frame: false,
      icon,
      modal: true,
      resizable: false,
      parent: BrowserWindow.fromWebContents(event.sender)!,
      autoHideMenuBar: true,
      webPreferences: {
        preload: resolve(__dirname, '../preload/index.js'),
        sandbox: false
      }
    })
    dialogModalWindow.on('maximize', () => {
      dialogModalWindow?.webContents.send('application:toggle-maximize-window', true)
    })
    dialogModalWindow.on('unmaximize', () => {
      dialogModalWindow?.webContents.send('application:toggle-maximize-window', false)
    })
    dialogModalWindow.loadURL(getOpenUrl(data.url))
    dialogModalWindow.once('show', () => {
      setTimeout(() => {
        dialogModalWindow?.webContents.send('application:dialog-data', data.ext)
      }, 500);
    })
    dialogModalWindow?.show()
    dialogModalWindow.on('closed', () => {
      dialogModalWindow = null;
    })
  })

  /**
   * 检查更新页面
   */
  let checkUpdateWindow: Electron.BrowserWindow | null = null
  ipcMain.on('application:open-check-update', () => {
    if (checkUpdateWindow && checkUpdateWindow.isVisible()) {
      focusWindow(checkUpdateWindow)
      return
    }
    checkUpdateWindow = openWindow({
      width: 590 + offsetWindowSize * 2,
      height: 400  + offsetWindowSize * 2,
      resizable: false,
      url: '/app/checkUpdate',
    })
    checkUpdateWindow?.center()
    checkUpdateWindow.show()
    checkUpdateWindow.on('closed', () => {
      checkUpdateWindow = null;
    })
    checkUpdate(checkUpdateWindow)
  })

  /**
   * 更新下载页面
   */
  let downloadWin: Electron.BrowserWindow | null = null
  ipcMain.on('application:immediately-update', (event) => {
    event.sender.close()
    if (downloadWin && downloadWin.isVisible()) {
      focusWindow(downloadWin)
      return
    }
    downloadWin = openWindow({
      width: 300,
      height: 80,
      resizable: false,
      url: '/app/downloadUpdate',
    })
    downloadWin?.setPosition(width - 300, height - 80)
    downloadWin?.show()
    downloadWin?.on('closed', ()=> {
      downloadWin = null
    })
    setDownloadWin(downloadWin)
  })
  /**
   * 下载完成提示页面
   */
  let downloadTipsWin: Electron.BrowserWindow | null = null
  ipcMain.on('application:show-download-tips', (event) => {
    event.sender.close()
    if (downloadTipsWin && downloadTipsWin.isVisible()) {
      focusWindow(downloadTipsWin)
      return
    }
    downloadTipsWin = openWindow({
      width: 300,
      height: 160,
      url: '/app/downloadedUpdateTips',
    })
    downloadTipsWin.center()
    downloadTipsWin.show()
    downloadTipsWin?.on('closed', ()=> {
      downloadTipsWin = null
    })
  })


  ipcMain.on('open-url', (_, url) => {
    shell.openExternal(url);
  });

  ipcMain.on('application:always-on-top-window', (event, value) => {
    const win = BrowserWindow.fromWebContents(event.sender);
    if (win) {
      win?.setAlwaysOnTop(value)
    }
  })
  ipcMain.on('application:close-window', (event) => {
    event.sender.close()
  })
  ipcMain.on('application:minimize-window', (event) => {
    const win = BrowserWindow.fromWebContents(event.sender);
    if (win?.isMinimizable()) {
      win.minimize()
    }
  })
  ipcMain.on('application:toggle-maximize-window', (event) => {
    const win = BrowserWindow.fromWebContents(event.sender);
    if (win?.isMaximized()) {
      win?.unmaximize()
    } else {
      win?.maximize()
    }
  })
}

app.whenReady().then(() => {
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })
  main()
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
    killServer()
  }
})
